package com.eds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.eds.dao.RedisDao;
import com.eds.dto.BackBoardDTO;
import com.eds.exception.BusException;
import com.eds.feign.CourseFeign;
import com.eds.feign.OssFeign;
import com.eds.feign.SmsFeign;
import com.eds.jwt.utils.JwtUtils;
import com.eds.log.LogUtil;
import com.eds.mapper.OssImageMapper;
import com.eds.mapper.UserMapper;
import com.eds.mapper.UserPreferenceMapper;
import com.eds.pojo.BaseResult;
import com.eds.pojo.CodeEnum;
import com.eds.service.TeacherScheduleService;
import com.eds.service.TeacherService;
import com.eds.service.UserService;
import com.eds.utils.Md5Util;
import com.eds.utils.RandomUtil;
import com.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName：UserServiceImpl
 * @Author: vvSmile
 * @Date: 2025/03/14
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SmsFeign smsFeign;
    @Autowired
    private OssFeign ossFeign;
    @Autowired
    private CourseFeign courseFeign;
    @Autowired
    private RedisDao<String> redisDao;
    @Autowired
    private UserPreferenceMapper userPreferenceMapper;
    @Autowired
    private OssImageMapper ossImageMapper;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private TeacherScheduleService teacherScheduleService;



    /* *
     * @Title: loginByUsernamePassword
     * @Author: vvSmile
     * @Date: 2025-03-14 20:13:04
     * @param user
     * @return String
     * @Description: TODO 登录进行验证，验证成功返回token
     */
    @LcnTransaction
    @Transactional
    @Override
    public BaseResult loginByUsernamePassword(User user) {
        //校验用户名和密码
        if (!StringUtils.hasText(user.getUserName()) || !StringUtils.hasText(user.getPassword())) {
            throw new BusException(CodeEnum.LOGIN_NAME_OR_PASSWORD_IS_NULL.getCode(), CodeEnum.LOGIN_NAME_OR_PASSWORD_IS_NULL.getMessage());
        }
        //根据用户名查询账户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUserName());
        queryWrapper.or();
        queryWrapper.eq("mobile", user.getUserName());
        User userReturn = userMapper.selectOne(queryWrapper);
        //校验密码
        if (userReturn == null || !Md5Util.verify(user.getPassword(), userReturn.getPassword())) {
            throw new BusException(CodeEnum.LOGIN_NAME_OR_PASSWORD_ERROR.getCode(), CodeEnum.LOGIN_NAME_OR_PASSWORD_ERROR.getMessage());
        }
        //生成登录token
        String token = JwtUtils.signWithRoles(userReturn.getUserId(), userReturn.getUserName(), userReturn.getRole());
        if (token.isEmpty()) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        //记录最后登录时间
        userReturn.setLastLoginDate(new Date());
        int updateLastLoginDate = userMapper.updateById(userReturn);
        if (updateLastLoginDate < 0) {
            throw new BusException(CodeEnum.UPDATE_LAST_LOGIN_DATE_ERROR.getCode(), CodeEnum.UPDATE_LAST_LOGIN_DATE_ERROR.getMessage());
        }
        return BaseResult.ok("登录成功", token, userReturn.getRole());

    }

    /* *
     * @Title: registerService
     * @Author: vvSmile
     * @Date: 2025-03-14 20:21:48
     * @param shoppingUser
     * @return boolean
     * @Description: TODO 通过用户信息进行注册
     */
    @LcnTransaction
    @Transactional
    @Override
    public Long registerService(User user) {
        //1.校验账户是否被占用
        QueryWrapper<User> queryUsernameWrapper = new QueryWrapper<>();
        queryUsernameWrapper.eq("username", user.getUserName());
        queryUsernameWrapper.or();
        queryUsernameWrapper.eq("mobile", user.getUserName());
        User userNameReturn = userMapper.selectOne(queryUsernameWrapper);
        if (userNameReturn != null) {
            throw new BusException(CodeEnum.USERNAME_OR_PHONE_REGISTED.getCode(), CodeEnum.USERNAME_OR_PHONE_REGISTED.getMessage());
        }
        //2.校验手机号是否被占用
        QueryWrapper<User> queryMobileWrapper = new QueryWrapper<>();
        queryMobileWrapper.eq("username", user.getMobile());
        queryMobileWrapper.or();
        queryMobileWrapper.eq("mobile", user.getMobile());
        User userMobileReturn = userMapper.selectOne(queryUsernameWrapper);
        if (userMobileReturn != null) {
            throw new BusException(CodeEnum.USERNAME_OR_PHONE_REGISTED.getCode(), CodeEnum.USERNAME_OR_PHONE_REGISTED.getMessage());
        }
        //3. 完成注册
        user.setPassword(Md5Util.encode(user.getPassword()));//密码加密
        int register = userMapper.insert(user);
        LogUtil.info(UserService.class, "新用户注册", user.getUserName());
        if (register < 0) {
            throw new BusException(CodeEnum.REGISTER_ERROR.getCode(), CodeEnum.REGISTER_ERROR.getMessage());

        }
        //获取默认头像
        //获取默认头像地址
        OssImage defaultImage = ossFeign.getDefaultImage();
        if (defaultImage == null) {
            throw new BusException(CodeEnum.GET_DEFAULT_HEAD_ERROR.getCode(), CodeEnum.GET_DEFAULT_HEAD_ERROR.getMessage());
        }
        //查询新增后的用户id
        //User user1 = userMapper.selectOne(queryUsernameWrapper);
        OssImage ossImage = new OssImage();
        ossImage.setUserId(user.getUserId());
        ossImage.setUrl(defaultImage.getUrl());
        ossImage.setDescription("注册的默认头像");
        ossImage.setUploadTime(new Date());
        ossImage.setRelationType("head");
        int updateHead = ossImageMapper.insert(ossImage);
        if (updateHead < 0) {
            throw new BusException(CodeEnum.UPDATE_HEAD_ERROR.getCode(), CodeEnum.UPDATE_HEAD_ERROR.getMessage());
        }
        UserPreference userPreference = new UserPreference();
        userPreference.setUserId(user.getUserId());
        int registerCreatPreference = userPreferenceMapper.insert(userPreference);
        if (registerCreatPreference < 0) {
            throw new BusException(CodeEnum.REGISTER_CREATE_PREFERENCE_ERROR.getCode(), CodeEnum.REGISTER_CREATE_PREFERENCE_ERROR.getMessage());
        }
        if (updateHead < 0 || register < 0)
            return 0L;
        return user.getUserId();
    }


    /* *
     * @Title: getUserLoginUsernameService
     * @Author: vvSmile
     * @Date: 2025-03-14 20:22:07
     * @param token
     * @return String
     * @Description: TODO 获取登录的用户名
     */
    @Override
    public User getUserLoginUsernameService(String token) {
        //获取Token
        User userInfoByToken = getUserInfoByToken(token);
        if (userInfoByToken == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        QueryWrapper<OssImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userInfoByToken.getUserId());
        queryWrapper.eq("relation_type", "head");
        OssImage ossImageSelect = ossImageMapper.selectOne(queryWrapper);
        if (ossImageSelect == null) {
            throw new BusException(CodeEnum.GET_HEAD_ERROR.getCode(), CodeEnum.GET_HEAD_ERROR.getMessage());
        }
        ArrayList<OssImage> ossImages = new ArrayList<>();
        ossImages.add(ossImageSelect);
        userInfoByToken.setOssImages(ossImages);
        userInfoByToken.setMobile("");
        userInfoByToken.setPassword("");
        userInfoByToken.setIdCard("");
        userInfoByToken.setRealName("");
        return userInfoByToken;
    }


    /* *
     * @Title: sendRegisterMessageCodeService
     * @Author: vvSmile
     * @Date: 2025-03-14 20:22:26
     * @param phone
     * @return boolean
     * @Description: TODO Register发短信
     */
    @Override
    public boolean sendRegisterMessageCodeService(String mobile) {
        boolean sendMessageCodeReturn = onlySendMessageCodeService("user:register:", mobile);
        if (!sendMessageCodeReturn)
            return false;
        return true;
    }



    /* *
     * @Title: checkRegisterMessageCodeService
     * @Author: vvSmile
     * @Date: 2025-03-14 20:22:37
     * @param phone
     * @param userCode
     * @return Boolean
     * @Description: TODO 注册短信验证
     */
    @Override
    public Boolean checkRegisterMessageCodeService(String mobile, String userCode) {
        Boolean onlyCheckMessageReturn = onlyCheckMessageCodeService("user:register:", mobile, userCode);
        if (onlyCheckMessageReturn==false)
            return false;
        return true;
    }


    /* *
     * @Title: sendLoginMessageCodeService
     * @Author: vvSmile
     * @Date: 2025-03-14 20:22:26
     * @param phone
     * @return boolean
     * @Description: TODO Login发短信
     */
    @Override
    public boolean sendLoginMessageCodeService(String mobile) {
        boolean sendMessageCodeReturn = onlySendMessageCodeService("user:login:", mobile);
        if (!sendMessageCodeReturn)
            return false;
        return true;
    }


    /* *
     * @Title: checkLoginMessageCodeService
     * @Author: vvSmile
     * @Date: 2025-03-14 20:22:37
     * @param phone
     * @param userCode
     * @return Boolean
     * @Description: TODO Login短信验证
     */
    @Override
    public BaseResult checkLoginMessageCodeService(String mobile, String userCode) {
        Boolean onlyCheckMessageReturn = onlyCheckMessageCodeService("user:login:", mobile, userCode);
        //通过手机号查询用户信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("mobile", mobile);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            throw new BusException(CodeEnum.SELECT_USER_INFO_BY_MOBILE_ERROR.getCode(), CodeEnum.SELECT_USER_INFO_BY_MOBILE_ERROR.getMessage(), null);
        }
        //生成登录token
        String token = JwtUtils.signWithRoles(user.getUserId(), user.getUserName(),user.getRole());
        if (token.isEmpty()) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        //记录最后登录时间
        user.setLastLoginDate(new Date());
        int updateLastLoginDate = userMapper.updateById(user);
        if (updateLastLoginDate < 0) {
            throw new BusException(CodeEnum.UPDATE_LAST_LOGIN_DATE_ERROR.getCode(), CodeEnum.UPDATE_LAST_LOGIN_DATE_ERROR.getMessage());
        }
        if (!onlyCheckMessageReturn) {
            return BaseResult.error(CodeEnum.LOGIN_ERROR);
        }
        return BaseResult.ok("登录成功", token, user.getRole());
    }



    /* *
     * @Title: sendMessageCodeService
     * @Author: vvSmile
     * @Date: 2025-03-14 20:22:26
     * @param phone
     * @return boolean
     * @Description: TODO 只发短信
     */
    public boolean onlySendMessageCodeService(String redisPre,String mobile) {
        //α．生成四位随机验证码
        String code = RandomUtil.buildSmsCode(4);
        //b．远程调用短信服务发送验证
        BaseResult baseResult = smsFeign.sendSmsCode(mobile, code);
        //c．缓存注册验证码到redis中(缓存5分钟)
        if (baseResult.getCode()==200)
            redisDao.set(redisPre+mobile,code,5, TimeUnit.MINUTES);
        else
            return false;
        System.out.println("注册的验证码 = " + code);
        return true;

    }


    /* *
     * @Title: checkMessageCodeService
     * @Author: vvSmile
     * @Date: 2025-03-14 20:22:37
     * @param phone
     * @param userCode
     * @return Boolean
     * @Description: TODO 只校验短信
     */
    public Boolean onlyCheckMessageCodeService(String redisPre,String mobile, String userCode) {
        //a. 获取Redis中缓存的验证码
        String sysCode = redisDao.get( redisPre+ mobile);
        if (sysCode == null || !sysCode.equals(userCode)) {
            throw new BusException(CodeEnum.REGISTER_CODE_ERROR.getCode(), CodeEnum.REGISTER_CODE_ERROR.getMessage());
        }
        return true;
    }


    /* *
     * @Title: resetPasswordService
     * @Author: vvSmile
     * @Date: 2025-03-16 10:54:00
     * @param user
     * @return Boolean
     * @Description: TODO 重置密码
     */
    @Override
    public Boolean resetPasswordService(User user) {
        // 1. 校验输入参数是否为空
        if (user == null || StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getMobile()) || StringUtils.isEmpty(user.getPassword())) {
            throw new BusException(CodeEnum.PARAM_ERROR.getCode(), CodeEnum.PARAM_ERROR.getMessage());
        }
        // 2. 根据用户名查找用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUserName());
        User userResult = userMapper.selectOne(queryWrapper);
        // 3. 验证用户名是否存在以及手机号是否匹配
        if (userResult == null || !userResult.getMobile().equals(user.getMobile())) {
            new BusException(CodeEnum.USERNAME_ID_NULL_OR_PHONE_ERROR.getCode(), CodeEnum.USERNAME_ID_NULL_OR_PHONE_ERROR.getMessage());// 用户名不存在或手机号不匹配
        }
        // 4. 更新用户的新密码
        userResult.setPassword(Md5Util.encode(user.getPassword()));
        // 5. 执行更新操作
        int updateNewPassword = userMapper.updateById(userResult);
        // 6. 返回更新结果
        return updateNewPassword > 0;
    }



    /* *
     * @Title: sendResetMessageCodeService
     * @Author: vvSmile
     * @Date: 2025-03-16 10:53:19
     * @param mobile
     * @return boolean
     * @Description: TODO 重置密码发送短信
     */
    @Override
    public boolean sendResetMessageCodeService(String mobile) {
        boolean sendMessageCodeReturn = onlySendMessageCodeService("user:reset:", mobile);
        if (!sendMessageCodeReturn)
            return false;
        return true;
    }




    /* *
     * @Title: checkResetMessageCodeService
     * @Author: vvSmile
     * @Date: 2025-03-16 10:54:11
     * @param mobile
     * @param userCode
     * @return Boolean
     * @Description: TODO 重置密码校验短信
     */
    @Override
    public Boolean checkResetMessageCodeService(String mobile, String userCode) {
        Boolean onlyCheckMessageReturn = onlyCheckMessageCodeService("user:reset:", mobile, userCode);
        if (onlyCheckMessageReturn == false)
            return false;
        return true;
    }


    /* *
     * @Title: getUserDetailsInfoService
     * @Author: vvSmile
     * @Date: 2025-03-18 20:15:34
     * @return User
     * @Description: TODO 获取用户详细信息
     */
    @Override
    public User getUserDetailsInfoService(String token) {
        //根据token获取用户数据
        User userInfoByToken = getUserInfoByToken(token);
        if (userInfoByToken == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        if (userInfoByToken.getRole().equals("student")) {
            //获取用户兴趣
            QueryWrapper<UserPreference> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userInfoByToken.getUserId());
            UserPreference userPreference = userPreferenceMapper.selectOne(wrapper);
            if (userPreference == null) {
                throw new BusException(CodeEnum.SELECT_USER_PREFERENCE_ERROR.getCode(), CodeEnum.SELECT_USER_PREFERENCE_ERROR.getMessage());
            }
            //添加进user里
            userInfoByToken.setUserPreferences(userPreference);
        }
        //查询头像
        QueryWrapper<OssImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userInfoByToken.getUserId());
        queryWrapper.eq("relation_type", "head");
        OssImage ossImage = ossImageMapper.selectOne(queryWrapper);
        if (ossImage == null) {
            throw new BusException(CodeEnum.GET_HEAD_ERROR.getCode(), CodeEnum.GET_HEAD_ERROR.getMessage());
        }
        ArrayList<OssImage> ossImages = new ArrayList<>();
        ossImages.add(ossImage);
        userInfoByToken.setOssImages(ossImages);
        return userInfoByToken;
    }

    /* *
     * @Title: updateUserInfo
     * @Author: vvSmile
     * @Date: 2025-03-18 20:28:18
     * @param user
     * @return User
     * @Description: TODO 修改用户信息（第一次，必须填姓名和身份证号）
     */
    @LcnTransaction
    @Transactional
    @Override
    public Boolean updateUserInfo(String token, User user) {
        User userInfoByToken = getUserInfoByToken(token);
        if (userInfoByToken == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        user.setUserId(userInfoByToken.getUserId());
        if (user.getUserPreferences() != null) {
            user.getUserPreferences().setUserId(userInfoByToken.getUserId());
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userInfoByToken.getUserId());
        //检查字段是否有需要更新
        boolean hasUpdate = false;
        if (user.getUserName() != null) {
            updateWrapper.set("username", user.getUserName());
            hasUpdate = true;
        }
        if (user.getEmail() != null) {
            updateWrapper.set("email", user.getEmail());
            hasUpdate = true;
        }
        if (user.getRealName() != null) {
            updateWrapper.set("real_name", user.getRealName());
            hasUpdate = true;
        }
        if (user.getIdCard() != null) {
            updateWrapper.set("id_card", user.getIdCard());
            hasUpdate = true;
        }
        if (user.getGender() != null) {
            updateWrapper.set("gender", user.getGender());
            hasUpdate = true;
        }
        if (user.getBirthDate() != null) {
            updateWrapper.set("birth_date", user.getBirthDate());
            hasUpdate = true;
        }
        if (user.getEducation() != null) {
            updateWrapper.set("education", user.getEducation());
            hasUpdate = true;
        }
        if (user.getSchool() != null) {
            updateWrapper.set("school", user.getSchool());
            hasUpdate = true;
        }
        // 如果没有字段需要更新，直接返回错误
        if (!hasUpdate) {
            throw new BusException(CodeEnum.LEAST_ONE_FIELD_BE_UPDATED.getCode(), CodeEnum.LEAST_ONE_FIELD_BE_UPDATED.getMessage());
        }
        //修改用户信息
        int updateReturn = userMapper.update(null, updateWrapper);
        if (updateReturn < 0) {
            throw new BusException(CodeEnum.UPDATE_USER_INFO_ERROR.getCode(), CodeEnum.UPDATE_USER_INFO_ERROR.getMessage());
        }
        user.getUserPreferences().setUserId(userInfoByToken.getUserId());
        //修改对应的喜好
        int updatePreference = userPreferenceMapper.updateById(user.getUserPreferences());
        if (updatePreference < 0) {
            throw new BusException(CodeEnum.UPDATE_PREFERENCE_ERROR.getCode(), CodeEnum.UPDATE_PREFERENCE_ERROR.getMessage());
        }
        return updateReturn > 0 && updatePreference > 0;
    }


    /* *
     * @Title: updateUserPhone
     * @Author: vvSmile
     * @Date: 2025-03-18 21:11:42
     * @param token
     * @param user
     * @return Boolean
     * @Description: TODO 修改用户手机号（必须填用户名验证）
     */
    @Override
    public Boolean updateUserPhone(String token, User user) {
        User userInfoByToken = getUserInfoByToken(token);
        if (userInfoByToken == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        if (!user.getUserName().equals(userInfoByToken.getUserName())) {
            throw new BusException(CodeEnum.DIFFERENT_INFO.getCode(), CodeEnum.DIFFERENT_INFO.getMessage());
        }
        user.setUserId(userInfoByToken.getUserId());
        int i = userMapper.updateById(user);
        if (i < 0) {
            throw new BusException(CodeEnum.UPDATE_USER_INFO_ERROR.getCode(), CodeEnum.UPDATE_USER_INFO_ERROR.getMessage());
        }
        return true;
    }

    /* *
     * @Title: upload
     * @Author: vvSmile
     * @Date: 2025-03-27 21:10:57
     * @param token
     * @param file
     * @return BaseResult
     * @Description: TODO 上传头像
     */
    @LcnTransaction
    @Transactional
    @Override
    public BaseResult upload(String token, MultipartFile file) {
        //获取上传地址
        BaseResult upload = ossFeign.upload(file);
        if (upload.getData() == null) {
            throw new BusException(CodeEnum.UPLOAD_HEAD_ERROR.getCode(), CodeEnum.UPLOAD_HEAD_ERROR.getMessage());
        }
        //获取用户信息
        User userInfoByToken = getUserInfoByToken(token);
        if (userInfoByToken == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        //查询用户的头像
        QueryWrapper<OssImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userInfoByToken.getUserId());
        queryWrapper.eq("relation_type", "head");
        OssImage ossImageSelect = ossImageMapper.selectOne(queryWrapper);
        if (ossImageSelect == null) {
            throw new BusException(CodeEnum.GET_HEAD_ERROR.getCode(), CodeEnum.GET_HEAD_ERROR.getMessage());
        }
        //获取头像id
        Long imageId = ossImageSelect.getImageId();
        //删除记录
        int i = ossImageMapper.deleteById(imageId);
        //新建头像地址
        OssImage ossImage = new OssImage();
        ossImage.setUserId(userInfoByToken.getUserId());
        ossImage.setUrl((String) upload.getData());
        ossImage.setRelationType("head");
        //新建
        int insert = ossImageMapper.insert(ossImage);
        if (i < 0 || insert < 0)
            return BaseResult.error(CodeEnum.UPLOAD_HEAD_ERROR);
        return BaseResult.ok("上传头像成功！" + upload.getData());
    }

    @Override
    public Long getUserIdFromToken(String token) {
        User userInfoByToken = getUserInfoByToken(token);
        if (userInfoByToken == null) {
            throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
        }
        return userInfoByToken.getUserId();
    }

    //通过课程Id查询用户信息
    @Override
    public User getUserInfoByUserId(Long userId) {
        //查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusException(CodeEnum.SELECT_USER_INFO_BY_USERID_ERROR.getCode(), CodeEnum.SELECT_USER_INFO_BY_USERID_ERROR.getMessage());
        }
        //查询头像那个信息
        QueryWrapper<OssImage> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", userId);
        queryWrapper1.eq("relation_type", "head");
        OssImage ossImage = ossImageMapper.selectOne(queryWrapper1);
        if (ossImage == null) {
            throw new BusException(CodeEnum.GET_HEAD_ERROR.getCode(), CodeEnum.GET_HEAD_ERROR.getMessage());
        }
        ArrayList<OssImage> ossImages = new ArrayList<>();
        ossImages.add(ossImage);
        user.setOssImages(ossImages);
        //查询老师信息
        if (!user.getRole().equals("teacher")) {
            return null;
        }
        //根据用户id查寻老师信息
        Teacher teacher = teacherService.selectTeacherInfoByUserId(userId);

        //查询可用课程表
        List<TeacherSchedule> teacherSchedules = teacherScheduleService.selectTeacherSchedules(teacher.getTeacherId());
        teacher.setTeacherSchedule(teacherSchedules);
        //将老师信息加入用户中
        user.setTeacher(teacher);
        return user;
    }


    /* *
     * @Title: getUserByUserId
     * @Author: vvSmile
     * @Date: 2025-04-06 21:00:55
     * @param userId
     * @return User
     * @Description: TODO 通过用户id查询用户信息
     */
    @Override
    public User getUserByUserId(Long userId) {
        //查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusException(CodeEnum.SELECT_USER_INFO_BY_USERID_ERROR.getCode(), CodeEnum.SELECT_USER_INFO_BY_USERID_ERROR.getMessage());
        }
        //查询头像那个信息
        QueryWrapper<OssImage> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", userId);
        queryWrapper1.eq("relation_type", "head");
        OssImage ossImage = ossImageMapper.selectOne(queryWrapper1);
        if (ossImage == null) {
            throw new BusException(CodeEnum.GET_HEAD_ERROR.getCode(), CodeEnum.GET_HEAD_ERROR.getMessage());
        }
        ArrayList<OssImage> ossImages = new ArrayList<>();
        ossImages.add(ossImage);
        user.setOssImages(ossImages);
        //获取用户兴趣
        QueryWrapper<UserPreference> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", user.getUserId());
        UserPreference userPreference = userPreferenceMapper.selectOne(wrapper);
        if (userPreference == null) {
            throw new BusException(CodeEnum.SELECT_USER_PREFERENCE_ERROR.getCode(), CodeEnum.SELECT_USER_PREFERENCE_ERROR.getMessage());
        }
        //添加进user里
        user.setUserPreferences(userPreference);
        return user;
    }


    /* *
     * @Title: verifyToken
     * @Author: vvSmile
     * @Date: 2025-04-07 19:06:19
     * @param token
     * @return Boolean
     * @Description: TODO 验证token
     */
    @Override
    public Boolean verifyToken(String token, Long userId) {
        Long userIdReturn = getUserIdFromToken(token);
        if (userIdReturn.equals(userId)) {
            return true;
        }
        return false;
    }

    /* *
     * @Title: getAllTeachersCourses
     * @Author: vvSmile
     * @Date: 2025-04-09 18:57:38
     * @return List<Course>
     * @Description: TODO 描述方法主要功能
     */
    @Override
    public List<User> getAllTeachersCourses() {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("role", "teacher");
        List<User> users = userMapper.selectList(userQueryWrapper);
        for (User user : users) {
            //根据用户id查寻老师信息
            Teacher teacher = teacherService.selectTeacherInfoByUserId(user.getUserId());
            user.setTeacher(teacher);
            //查询课程信息
            List<Course> courses = courseFeign.selectCourseByTeacherIdAIUsed(teacher.getUserId());
            user.setCourses(courses);
        }
        return users;
    }


    /* *
     * @Title: getAllUser
     * @Author: vvSmile
     * @Date: 2025-04-10 15:37:55
     * @return List<User>
     * @Description: TODO 获取所有用户信息
     */
    @Override
    public List<User> getAllUser() {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("role", "student");
        List<User> users = userMapper.selectList(userQueryWrapper);
        return users;
    }


    /* *
     * @Title: getUserAvatarByName
     * @Author: vvSmile
     * @Date: 2025-04-15 17:49:00
     * @param userName
     * @return String
     * @Description: TODO 通过用户名查询用户头像
     */
    @Override
    public String getUserAvatarByName(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            QueryWrapper<OssImage> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id", user.getUserId());
            queryWrapper1.eq("relation_type", "head");
            OssImage ossImage = ossImageMapper.selectOne(queryWrapper1);
            if (ossImage != null) {
                return ossImage.getUrl();
            }
        }
        return null;
    }


    /* *
     * @Title: getAllUsers
     * @Author: vvSmile
     * @Date: 2025-05-05 16:25:00
     * @return BaseResult
     * @Description: TODO 获取所有用户
     */
    @Override
    public BaseResult getAllUsers(String userName) {
        QueryWrapper<User> queryWrapperUser = new QueryWrapper<>();

        if (userName != null) {
            queryWrapperUser.like("username", userName);
        } else {
            queryWrapperUser.in("role", "teacher", "student");
        }
        List<User> users = new ArrayList<>();
        for (User user : userMapper.selectList(queryWrapperUser)) {
            //查询头像
            QueryWrapper<OssImage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getUserId());
            queryWrapper.eq("relation_type", "head");
            OssImage ossImage = ossImageMapper.selectOne(queryWrapper);
            if (ossImage == null) {
                throw new BusException(CodeEnum.GET_HEAD_ERROR.getCode(), CodeEnum.GET_HEAD_ERROR.getMessage());
            }
            ArrayList<OssImage> ossImages = new ArrayList<>();
            ossImages.add(ossImage);
            user.setOssImages(ossImages);
            users.add(user);
        }
        if (users.size() > 0) {
            return BaseResult.ok(users);
        }
        return BaseResult.error(CodeEnum.SELECT_USER_ERROR);
    }

    /* *
     * @Title: updateUserRole
     * @Author: vvSmile
     * @Date: 2025-05-05 16:42:50
     * @param user
     * @return BaseResult
     * @Description: TODO 修改用户权限
     */
    @Override
    public BaseResult updateUserRole(User user) {
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        //如果role和status不为空，则修改role和status
        if (user.getRole() != null && user.getStatus() != null) {
            userUpdateWrapper.eq("user_id", user.getUserId())
                    .set("role", user.getRole())
                    .set("status", user.getStatus());
        } else if (user.getRole() != null) {
            userUpdateWrapper.eq("user_id", user.getUserId())
                    .set("role", user.getRole());
        } else if (user.getStatus() != null) {
            userUpdateWrapper.eq("user_id", user.getUserId())
                    .set("status", user.getStatus());
        }
        int update = userMapper.update(null, userUpdateWrapper);
        if (update > 0) {
            return BaseResult.ok();
        }
        return null;
    }

    /* *
     * @Title: deleteUser
     * @Author: vvSmile
     * @Date: 2025-05-05 16:45:49
     * @param user
     * @return BaseResult
     * @Description: TODO 删除用户
     */
    @Override
    @LcnTransaction
    public BaseResult deleteUser(User user) {
        int i = userMapper.deleteById(user.getUserId());
        QueryWrapper<UserPreference> eqed = new QueryWrapper<UserPreference>().eq("user_id", user.getUserId());
        int delete = userPreferenceMapper.delete(eqed);
        //查询头像
        QueryWrapper<OssImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getUserId());
        int delete1 = ossImageMapper.delete(queryWrapper);
        if (user.getRole().equals("teacher")) {
            teacherService.deleteTeacher(user.getUserId());
        }
        if (i > 0 && delete > 0 && delete1 > 0) {
            return BaseResult.ok();
        }
        return BaseResult.error(CodeEnum.DELETE_USER_ERROR);
    }

    @Override
    public BackBoardDTO getUserBoard() {
        //获取所有用户的个数
        int totalUser = userMapper.selectCount(null);
        //获取当天注册的用户个数
        int newUsersToday = userMapper.selectCount(new QueryWrapper<User>().apply("date(register_date)=date(now())"));
        //获取所有活跃的用户个数
        int activeUsers = userMapper.selectCount(new QueryWrapper<User>().apply("date(last_login_date)=date(now())"));
        //获取所有学生个数
        int students = userMapper.selectCount(new QueryWrapper<User>().eq("role", "student"));
        //获取所有教师个数
        int teachers = userMapper.selectCount(new QueryWrapper<User>().eq("role", "teacher"));
        //获取所有管理员个数
        int admins = userMapper.selectCount(new QueryWrapper<User>().eq("role", "root"));
        BackBoardDTO backBoardDTO = new BackBoardDTO();
        backBoardDTO.setTotalUser(totalUser);
        backBoardDTO.setNewUsersToday(newUsersToday);
        backBoardDTO.setActiveUsers(activeUsers);
        backBoardDTO.setStudents(students);
        backBoardDTO.setTeachers(teachers);
        backBoardDTO.setAdmins(admins);
        return backBoardDTO;
    }

    /* *
     * @Title: getTodayUserCount
     * @Author: vvSmile
     * @Date: 2025-05-06 00:38:19
     * @return List<User>
     * @Description: TODO 获取当天注册用户数量
     */
    @Override
    public List<User> getTodayUserCount() {
        //获取当天注册用户数量有多少
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("date(register_date)=date(now())");
        List<User> users = userMapper.selectList(queryWrapper);
        if (users.size() > 0) {
            return users;
        }
        return null;
    }


    //仅通过Token中查询用户信息
    private User getUserInfoByToken(String token) {
        //先查询是否有Token
        if (!StringUtils.hasText(token))
            return null;
        String[] tokenStr = token.split(" ");
        if (!"Bearer".equals(tokenStr[0])) {
            throw new BusException(CodeEnum.TOKEN_NOT_BEARER.getCode(), CodeEnum.TOKEN_NOT_BEARER.getMessage());
        }
        Map<String, Object> verify = JwtUtils.verify(tokenStr[1]);
        String s = (String) verify.get("userName");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", s);
        //根据token中的信息查用户信息
        User userReturn = userMapper.selectOne(queryWrapper);
        return userReturn;
    }

    //仅测试
    @Override
    public BaseResult test() {
        OssImage defaultImage = ossFeign.getDefaultImage();
        return BaseResult.ok(defaultImage);
    }


}
